import React from 'react';
import { Router, Switch, Route, Redirect, RouteProps } from 'react-router-dom';
import MyLoading from './components/Loading';
import history from './utils/history';
import { hasToken } from './utils/local';
const Layout = React.lazy(() => import('@/pages/layout'));
const Edit = React.lazy(() => import('@/pages/Profile/Edit'));
const Login = React.lazy(() => import('@/pages/login'));
const NotFound = React.lazy(() => import('@/pages/NotFound'));
const Chat = React.lazy(() => import('@/pages/Profile/Chat'));
const Search = React.lazy(() => import('@/pages/Search'));

export default function App() {
  return (
    <Router history={history}>
      <React.Suspense fallback={<MyLoading />}>
        <Switch>
          <Route path={'/login'} component={Login} />
          <Route path={'/search'} component={Search} />
          {/* <Route path={'/Profile/Edit'} component={Edit} /> */}
          <AuthRouter path={'/Profile/Edit'} component={Edit}></AuthRouter>
          <Route path={'/profile/chat'} component={Chat} />
          <Route path={'/'} component={Layout} />
          <Route path={'*'} component={NotFound} />
        </Switch>
      </React.Suspense>
    </Router>
  );
}
export type StateType = {
  from: string;
};
interface AuthRouterType extends RouteProps {
  component: React.FC<any>;
  path: string;
}
export function AuthRouter(props: AuthRouterType) {
  const { component: Coms, path, ...restProps } = props;
  return (
    <Route
      {...restProps}
      path={path}
      render={(_props) => {
        if (hasToken()) {
          return <Coms {..._props} />;
        }
        return (
          <Redirect
            to={{ pathname: '/login', state: { from: path } as StateType }}
          />
        );
      }}
    ></Route>
  );
}
